// 单独封装axios请求
import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
import router from '../router'
import Vue from 'vue'
const vm = new Vue()
// 创建一个实例
const request = axios.create({
  baseURL: '/conner',
  timeout: 8000
})

// 请求拦截
request.interceptors.request.use(function (config) {
  vm.$showLoading()
  // 处理头部token字段
  const token = localStorage.getItem('access_token')
  if (token) {
    // 请求头中添加token
    config.headers.access_token = token
  }
  // 处理post请求参数格式的问题
  if (config.method === 'post' && config.data) {
    config.data = qs.stringify(config.data)
  }
  return config
}, function (error) {
  // Do something with request error
  vm.$hideLoading()
  return Promise.reject(error)
})

// 响应拦截
request.interceptors.response.use(function (response) {
  vm.$hideLoading()
  // 判断 是否传token 或者token是否过期
  if (response.data.code === 403 || response.data.code === 402) {
    // 没有传token或者token过期了
    Toast(response.data.msg)
    // 跳转到登录页获取最新的token
    localStorage.removeItem('access_token')
    router.push('/login')
  }
  return response
}, function (error) {
  vm.$hideLoading()
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error)
})

export default request
